//
//  ViewController.swift
//  PhotoKitDemo
//
//  Created by 舒磊明 on 2019/2/21.
//  Copyright © 2019 舒磊明. All rights reserved.
//

import UIKit
import Photos

let AlbumCollectionCellIdentifier = "AlbumIdentifier"

class ViewController: UITableViewController {
    
    var smartAlbums: PHFetchResult<PHAssetCollection>! // 相册分类

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        title = "PhotoKitDemo"
        
        smartAlbums = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.albumRegular, options: nil)
        
        // 注册TableView Cell
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: AlbumCollectionCellIdentifier)
        
        // 关键：注册PHPhotoLibrary
        PHPhotoLibrary.shared().register(self)
    }
    
    //MARK: - TableView Delegate
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return smartAlbums.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: AlbumCollectionCellIdentifier)
        let collection = smartAlbums.object(at: indexPath.row)
        cell?.textLabel?.text = collection.localizedTitle
        return cell!
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let cell = tableView.cellForRow(at: indexPath) else { fatalError("Can not find sender") }
        let layout = collectionFlowLayout()
        let destination = AssetGridViewController(collectionViewLayout: layout)
        destination.title = cell.textLabel?.text
        destination.itemSize = layout.itemSize
        self.navigationController?.pushViewController(destination, animated: true)
    }
    
    // 设置Grid页面布局宽高
    func collectionFlowLayout() -> UICollectionViewFlowLayout {
        let layout = UICollectionViewFlowLayout()
        let margin: CGFloat = 5
        let layoutWH = (UIScreen.main.bounds.width - margin * 3) / 4
        layout.itemSize = CGSize(width: layoutWH, height: layoutWH)
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        return layout
    }
}

//MARK: - PHPhotoLibraryChangeObserver

extension ViewController: PHPhotoLibraryChangeObserver {
    func photoLibraryDidChange(_ changeInstance: PHChange) {

        // 修改通知可能来自后台线程
        // 切换到主线程来更新UI
        DispatchQueue.main.async {
            if let changeDetails = changeInstance.changeDetails(for: self.smartAlbums) {
                self.smartAlbums = changeDetails.fetchResultAfterChanges
                self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
            }
        }
    }
}
